package com.example.mybatis.config;

import com.example.mybatis.SexTypeEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Description:
 * mybatis类型解析器
 * @author zhouyu
 * @date 2022/2/24 15:05
 */
@MappedJdbcTypes(value = JdbcType.INTEGER, includeNullJdbcType = true)
public class SexEumTypeHandler extends BaseTypeHandler<SexTypeEnum> {
    private final Class<SexTypeEnum> type;

    public SexEumTypeHandler(Class<SexTypeEnum> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        } else {
            this.type = type;
        }
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, SexTypeEnum sexTypeEnum, JdbcType jdbcType) throws SQLException {
        if (jdbcType == null) {
            preparedStatement.setInt(i, sexTypeEnum.getValue());
        } else {
            preparedStatement.setObject(i, sexTypeEnum.name(), jdbcType.TYPE_CODE);
        }
    }

    @Override
    public SexTypeEnum getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        Integer value = resultSet.getInt(columnName);
        return value == null ? null : SexTypeEnum.getByValue(value);
    }

    @Override
    public SexTypeEnum getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        Integer value = resultSet.getInt(columnIndex);
        return value == null ? null : SexTypeEnum.getByValue(value);
    }

    @Override
    public SexTypeEnum getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        Integer value = callableStatement.getInt(columnIndex);
        return value == null ? null : SexTypeEnum.getByValue(value);
    }
}
